#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

void Usage(const std::string &process)
{
    std::cout << "Usage: " << process << " server_ip server_port"
              << std::endl;
}

enum class Status // C++11 强类型枚举
{
    NEW,          // 新建状态， 就是单纯的连接
    CONNECTING,   // 正在连接， 仅仅方便查询 conn 状态
    CONNECTED,    // 连接或者重连成功
    DISCONNECTED, // 重连失败
    CLOSED        // 连接失败， 经历重连， 无法连接
};

enum ExitCode
{
    USEAG_ERR=1,
    SOCKET_ERR
};

static const int defaultsockfd = -1;
static const int default_retry_interval = 1;
static const int default_max_retries = 5;

class ClientConnection
{
public:
    ClientConnection(uint16_t serverport, const std::string &serverip)
        : _sockfd(defaultsockfd)
        , _serverport(serverport)
        , _serverip(serverip)
        , _status(Status::NEW)
        , _retry_interval(default_retry_interval)
        , _max_retries(default_max_retries)
    {
    }
    Status GetStatus()
    {
        return _status;
    }
    void Connect()
    {
        _sockfd=socket(AF_INET,SOCK_STREAM,0);
        if(_sockfd<0)
        {
            std::cerr<<"sockfd create error"<<std::endl;
            exit(ExitCode::SOCKET_ERR);
        }
        struct sockaddr_in server;
        memset(&server,0,sizeof(server));
        server.sin_family=AF_INET;
        server.sin_port=htons(_serverport);
        inet_pton(AF_INET,_serverip.c_str(),&server.sin_addr);

        int n=connect(_sockfd,(struct sockaddr*)&server,sizeof(server));
        if(n<0)
        {
            //1.关闭sockfd
            Disconnect();
            //2.更新状态
            _status=Status::DISCONNECTED;
            //3.返回
            return;
        }
        _status=Status::CONNECTED;
        std::cout<<"connect success"<<std::endl;
    }
    void Reconnect()
    {
        int cnt=0;
        while(true)
        {
            Connect();
            if(_status==Status::CONNECTED)
            {
                break;
            }
            cnt++;
            if(cnt>_max_retries)
            {
                _status=Status::CLOSED;
                std::cout<<"链接失败，请检查你的网络"<<std::endl;
                break;
            }
            std::cout<<"断线重连中，当前链接次数："<<cnt<<std::endl;
            sleep(_retry_interval);
        }
    }
    void Process()//IO通信
    {
        while (true)
        {
            std::string message="hello server";
            ssize_t n=send(_sockfd,message.c_str(),message.size(),0);
            if(n>0)
            {   
                char buffer[1024];
                ssize_t m=recv(_sockfd,buffer,sizeof(buffer)-1,0);
                if(m>0)
                {
                    buffer[m]=0;
                    std::cout<<"echo server# "<<buffer<<std::endl;
                }
                else
                {
                    _status=Status::DISCONNECTED;
                    break;
                }
            }
            else
            {
                std::cerr<<"send error"<<std::endl;
                _status=Status::CLOSED;
                break;
            }
            sleep(1);
        }
    }
    void Disconnect()
    {
        if(_sockfd>defaultsockfd)
        {
            close(_sockfd);
            _status=Status::CLOSED;
            _sockfd=defaultsockfd;
        }
    }
    ~ClientConnection()
    {
    }

private:
    int _sockfd;
    uint16_t _serverport;  // server port 端口号
    std::string _serverip; // server ip 地址
    Status _status;        // 链接状态
    int _retry_interval;   // 重试时间间隔
    int _max_retries;      // 重试次数
};

class TcpClient
{
public:
    TcpClient(uint16_t serverport, const std::string &serverip) : _connection(serverport, serverip)
    {
    }
    void Excute()
    {
        while (true)
        {
            switch (_connection.GetStatus())
            {
            case Status::NEW:
                _connection.Connect();
                break;
            case Status::CONNECTED:
                _connection.Process();
                break;
            case Status::DISCONNECTED:
                _connection.Reconnect();
                break;
            case Status::CLOSED:
                _connection.Disconnect();
                return;
            default:
                break;
            }
        }
    }
    ~TcpClient()
    {
    }

private:
    ClientConnection _connection;
};

int main(int argc, char *argv[3])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    TcpClient tcpclient(serverport, serverip);
    tcpclient.Excute();
    return 0;
}


